package com.tianshi.agriculture.ui.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.tianshi.agriculture.databinding.FieldDebugAllLayoutBinding;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.BleController;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.callback.OnReceiverCallback;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.callback.OnWriteCallback;
import com.tianshi.agriculture.utils.ModbusUtils.ByteUtil;
import com.tianshi.agriculture.utils.ModbusUtils.ModbusError;
import com.tianshi.agriculture.utils.ModbusUtils.ModbusRTUHelper;
import com.tianshi.agriculture.utils.ToolsUtil;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class FieldDebugAllFragment extends Fragment {

    private FieldDebugAllLayoutBinding binding;
    public static final String REQUESTKEY_SENDANDRECIVEACTIVITY = "FieldDebugAllFragment";

    // Modbus地址定义（从0开始）- 这些地址需要根据实际情况调整
    // 用户设定区域 (20-59)
    private static final int ADDRESS_PRESSURE1_ZERO_CURRENT = 20;      // 压力传感器1_零点电流
    private static final int ADDRESS_PRESSURE1_FULL_CURRENT = 22;     // 压力传感器1_满度电流
    private static final int ADDRESS_PRESSURE1_ZERO_PRESSURE = 24;     // 压力传感器1_零点压力
    private static final int ADDRESS_PRESSURE1_FULL_PRESSURE = 26;     // 压力传感器1_满度压力
    private static final int ADDRESS_PRESSURE2_ZERO_CURRENT = 28;      // 压力传感器2_零点电流
    private static final int ADDRESS_PRESSURE2_FULL_CURRENT = 30;      // 压力传感器2_满度电流
    private static final int ADDRESS_PRESSURE2_ZERO_PRESSURE = 32;     // 压力传感器2_零点压力
    private static final int ADDRESS_PRESSURE2_FULL_PRESSURE = 34;     // 压力传感器2_满度压力
    private static final int ADDRESS_TEMP1_COEFF_A = 36;               // 温度传感器1_系数A
    private static final int ADDRESS_TEMP1_COEFF_B = 38;               // 温度传感器1_系数B
    private static final int ADDRESS_TEMP1_COEFF_C = 40;               // 温度传感器1_系数C
    private static final int ADDRESS_TEMP1_ZERO_DRIFT = 42;           // 温度传感器1_温度零漂
    private static final int ADDRESS_TEMP2_COEFF_A = 44;               // 温度传感器2_系数A
    private static final int ADDRESS_TEMP2_COEFF_B = 46;               // 温度传感器2_系数B
    private static final int ADDRESS_TEMP2_COEFF_C = 48;               // 温度传感器2_系数C
    private static final int ADDRESS_TEMP2_ZERO_DRIFT = 50;           // 温度传感器2_温度零漂
    private static final int ADDRESS_AUTO_CONTROL_P = 52;              // 自动控温-P系数
    private static final int ADDRESS_AUTO_CONTROL_I = 54;              // 自动控温-I系数
    private static final int ADDRESS_AUTO_CONTROL_D = 56;              // 自动控温-D系数
    private static final int ADDRESS_AUTO_CONTROL_PERIOD = 58;         // 自动控制周期

    // 出厂设定区域 (60-115)
    private static final int ADDRESS_PRESSURE1_ZERO_VOLTAGE = 60;      // 压力传感器1_零点电压
    private static final int ADDRESS_PRESSURE1_FULL_VOLTAGE = 62;      // 压力传感器1_满度电压
    private static final int ADDRESS_PRESSURE1_ZERO_CURRENT_FACTORY = 64; // 压力传感器1_零点电流(出厂)
    private static final int ADDRESS_PRESSURE1_FULL_CURRENT_FACTORY = 66; // 压力传感器1_满度电流(出厂)
    private static final int ADDRESS_PRESSURE2_ZERO_VOLTAGE = 68;      // 压力传感器2_零点电压
    private static final int ADDRESS_PRESSURE2_FULL_VOLTAGE = 70;      // 压力传感器2_满度电压
    private static final int ADDRESS_PRESSURE2_ZERO_CURRENT_FACTORY = 72; // 压力传感器2_零点电流(出厂)
    private static final int ADDRESS_PRESSURE2_FULL_CURRENT_FACTORY = 74; // 压力传感器2_满度电流(出厂)
    private static final int ADDRESS_DAC_ZERO = 76;                    // DAC输出零点
    private static final int ADDRESS_DAC_FULL = 78;                   // DAC输出满度
    private static final int ADDRESS_MULTI_TURN_ANGLE_ZERO = 80;      // 多圈角度传感器_零点角度
    private static final int ADDRESS_OPENING_ANGLE_ZERO = 82;         // 开度传感器_零点角度
    private static final int ADDRESS_OPENING_ANGLE_FULL = 84;         // 开度传感器_满度角度
    private static final int ADDRESS_OPENING_ZERO = 86;                // 开度传感器_零点开度
    private static final int ADDRESS_OPENING_FULL = 88;               // 开度传感器_满度开度
    private static final int ADDRESS_MAX_ROTATION_TURNS = 90;         // 最大转动圈数
    private static final int ADDRESS_SENSOR_VALIDITY_CONFIG = 92;      // 传感器有效性配置
    private static final int ADDRESS_TEMP_SENSOR_TYPE = 94;           // 温度传感器类型
    private static final int ADDRESS_EQUI_SERIAL_NUMBER = 93;         // equi序列号 (Uint32, 2个寄存器)
    private static final int ADDRESS_ANGLE_SENSOR_STALL_ADC = 95;      // 角度传感器堵转(ADC)
    private static final int ADDRESS_ANGLE_SENSOR_STALL_SECONDS = 96; // 角度传感器堵转(秒)
    private static final int ADDRESS_VALVE_OPENING_CONTROL_ERROR = 97; // 阀开度控制误差
    private static final int ADDRESS_ANGLE_SENSOR_SAMPLING_PERIOD = 98; // 角度传感器采样周期
    private static final int ADDRESS_MOTOR_STALL_CURRENT = 99;         // 电机堵转电流
    private static final int ADDRESS_TEMP1_ZERO_ORIGINAL_RESISTANCE = 100; // 温度传感器1_零点原始电阻
    private static final int ADDRESS_TEMP1_FULL_ORIGINAL_RESISTANCE = 102; // 温度传感器1_满度原始电阻
    private static final int ADDRESS_TEMP1_ZERO_RESISTANCE = 104;      // 温度传感器1_零点电阻
    private static final int ADDRESS_TEMP1_FULL_RESISTANCE = 106;      // 温度传感器1_满度电阻
    private static final int ADDRESS_TEMP2_ZERO_ORIGINAL_RESISTANCE = 108; // 温度传感器2_零点原始电阻
    private static final int ADDRESS_TEMP2_FULL_ORIGINAL_RESISTANCE = 110; // 温度传感器2_满度原始电阻
    private static final int ADDRESS_TEMP2_ZERO_RESISTANCE = 112;      // 温度传感器2_零点电阻
    private static final int ADDRESS_TEMP2_FULL_RESISTANCE = 114;      // 温度传感器2_满度电阻

    private static final int REGISTER_COUNT_FLOAT = 2;                 // Float类型需要2个寄存器
    private static final int REGISTER_COUNT_INT16 = 1;                 // Int16类型需要1个寄存器
    private static final int REGISTER_COUNT_UINT32 = 2;               // Uint32类型需要2个寄存器

    // 批量读取的起始地址和寄存器数量
    private static final int BATCH_READ_START_ADDRESS = 20;            // 起始地址
    private static final int BATCH_READ_REGISTER_COUNT = 96;           // 需要读取的寄存器数量 (从20到114，共96个寄存器)
    
    private boolean isBatchReading = false;  // 标记是否正在进行批量读取
    private Handler handler = new Handler(Looper.getMainLooper());  // 用于延迟执行读取操作

    // 地址到EditText的映射
    private Map<Integer, EditText> addressToEditTextMap = new HashMap<>();
    
    // 地址到数据类型的映射：0=Float, 1=Int16, 2=Uint32, 3=String(按Int16处理)
    private Map<Integer, Integer> addressToTypeMap = new HashMap<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        FieldDebugAllModel fieldDebugAllModel =
                new ViewModelProvider(this).get(FieldDebugAllModel.class);

        binding = FieldDebugAllLayoutBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化地址到EditText的映射
        initAddressMap();

        // 设置所有写入按钮的点击事件
        setupWriteButtons();

        // 读取所有按钮
        binding.readAllButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readAllValues();
            }
        });

        return root;
    }

    /**
     * 初始化地址到EditText的映射和地址到数据类型的映射
     */
    private void initAddressMap() {
        // 用户设定区域 - Float类型
        addressToEditTextMap.put(ADDRESS_PRESSURE1_ZERO_CURRENT, binding.valuePressure1ZeroCurrent);
        addressToTypeMap.put(ADDRESS_PRESSURE1_ZERO_CURRENT, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE1_FULL_CURRENT, binding.valuePressure1FullCurrent);
        addressToTypeMap.put(ADDRESS_PRESSURE1_FULL_CURRENT, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE1_ZERO_PRESSURE, binding.valuePressure1ZeroPressure);
        addressToTypeMap.put(ADDRESS_PRESSURE1_ZERO_PRESSURE, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE1_FULL_PRESSURE, binding.valuePressure1FullPressure);
        addressToTypeMap.put(ADDRESS_PRESSURE1_FULL_PRESSURE, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE2_ZERO_CURRENT, binding.valuePressure2ZeroCurrent);
        addressToTypeMap.put(ADDRESS_PRESSURE2_ZERO_CURRENT, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE2_FULL_CURRENT, binding.valuePressure2FullCurrent);
        addressToTypeMap.put(ADDRESS_PRESSURE2_FULL_CURRENT, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE2_ZERO_PRESSURE, binding.valuePressure2ZeroPressure);
        addressToTypeMap.put(ADDRESS_PRESSURE2_ZERO_PRESSURE, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE2_FULL_PRESSURE, binding.valuePressure2FullPressure);
        addressToTypeMap.put(ADDRESS_PRESSURE2_FULL_PRESSURE, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP1_COEFF_A, binding.valueTemp1CoeffA);
        addressToTypeMap.put(ADDRESS_TEMP1_COEFF_A, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP1_COEFF_B, binding.valueTemp1CoeffB);
        addressToTypeMap.put(ADDRESS_TEMP1_COEFF_B, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP1_COEFF_C, binding.valueTemp1CoeffC);
        addressToTypeMap.put(ADDRESS_TEMP1_COEFF_C, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP1_ZERO_DRIFT, binding.valueTemp1ZeroDrift);
        addressToTypeMap.put(ADDRESS_TEMP1_ZERO_DRIFT, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP2_COEFF_A, binding.valueTemp2CoeffA);
        addressToTypeMap.put(ADDRESS_TEMP2_COEFF_A, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP2_COEFF_B, binding.valueTemp2CoeffB);
        addressToTypeMap.put(ADDRESS_TEMP2_COEFF_B, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP2_COEFF_C, binding.valueTemp2CoeffC);
        addressToTypeMap.put(ADDRESS_TEMP2_COEFF_C, 0); // Float
        addressToEditTextMap.put(ADDRESS_TEMP2_ZERO_DRIFT, binding.valueTemp2ZeroDrift);
        addressToTypeMap.put(ADDRESS_TEMP2_ZERO_DRIFT, 0); // Float
        addressToEditTextMap.put(ADDRESS_AUTO_CONTROL_P, binding.valueAutoControlP);
        addressToTypeMap.put(ADDRESS_AUTO_CONTROL_P, 0); // Float
        addressToEditTextMap.put(ADDRESS_AUTO_CONTROL_I, binding.valueAutoControlI);
        addressToTypeMap.put(ADDRESS_AUTO_CONTROL_I, 0); // Float
        addressToEditTextMap.put(ADDRESS_AUTO_CONTROL_D, binding.valueAutoControlD);
        addressToTypeMap.put(ADDRESS_AUTO_CONTROL_D, 0); // Float
        addressToEditTextMap.put(ADDRESS_AUTO_CONTROL_PERIOD, binding.valueAutoControlPeriod);
        addressToTypeMap.put(ADDRESS_AUTO_CONTROL_PERIOD, 1); // Int16

        // 出厂设定区域
        addressToEditTextMap.put(ADDRESS_PRESSURE1_ZERO_VOLTAGE, binding.valuePressure1ZeroVoltage);
        addressToTypeMap.put(ADDRESS_PRESSURE1_ZERO_VOLTAGE, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE1_FULL_VOLTAGE, binding.valuePressure1FullVoltage);
        addressToTypeMap.put(ADDRESS_PRESSURE1_FULL_VOLTAGE, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE2_ZERO_VOLTAGE, binding.valuePressure2ZeroVoltage);
        addressToTypeMap.put(ADDRESS_PRESSURE2_ZERO_VOLTAGE, 0); // Float
        addressToEditTextMap.put(ADDRESS_PRESSURE2_FULL_VOLTAGE, binding.valuePressure2FullVoltage);
        addressToTypeMap.put(ADDRESS_PRESSURE2_FULL_VOLTAGE, 0); // Float
        addressToEditTextMap.put(ADDRESS_DAC_ZERO, binding.valueDacZero);
        addressToTypeMap.put(ADDRESS_DAC_ZERO, 1); // Int16
        addressToEditTextMap.put(ADDRESS_DAC_FULL, binding.valueDacFull);
        addressToTypeMap.put(ADDRESS_DAC_FULL, 1); // Int16
        addressToEditTextMap.put(ADDRESS_MULTI_TURN_ANGLE_ZERO, binding.valueMultiTurnAngleZero);
        addressToTypeMap.put(ADDRESS_MULTI_TURN_ANGLE_ZERO, 0); // Float
        addressToEditTextMap.put(ADDRESS_OPENING_ANGLE_ZERO, binding.valueOpeningAngleZero);
        addressToTypeMap.put(ADDRESS_OPENING_ANGLE_ZERO, 0); // Float
        addressToEditTextMap.put(ADDRESS_OPENING_ANGLE_FULL, binding.valueOpeningAngleFull);
        addressToTypeMap.put(ADDRESS_OPENING_ANGLE_FULL, 0); // Float
        addressToEditTextMap.put(ADDRESS_OPENING_ZERO, binding.valueOpeningZero);
        addressToTypeMap.put(ADDRESS_OPENING_ZERO, 0); // Float
        addressToEditTextMap.put(ADDRESS_OPENING_FULL, binding.valueOpeningFull);
        addressToTypeMap.put(ADDRESS_OPENING_FULL, 0); // Float
        addressToEditTextMap.put(ADDRESS_MAX_ROTATION_TURNS, binding.valueMaxRotationTurns);
        addressToTypeMap.put(ADDRESS_MAX_ROTATION_TURNS, 1); // Int16
        addressToEditTextMap.put(ADDRESS_SENSOR_VALIDITY_CONFIG, binding.valueSensorValidityConfig);
        addressToTypeMap.put(ADDRESS_SENSOR_VALIDITY_CONFIG, 3); // String(按Int16处理)
        addressToEditTextMap.put(ADDRESS_TEMP_SENSOR_TYPE, binding.valueTempSensorType);
        addressToTypeMap.put(ADDRESS_TEMP_SENSOR_TYPE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_EQUI_SERIAL_NUMBER, binding.valueEquiSerialNumber);
        addressToTypeMap.put(ADDRESS_EQUI_SERIAL_NUMBER, 2); // Uint32
        addressToEditTextMap.put(ADDRESS_ANGLE_SENSOR_STALL_ADC, binding.valueAngleSensorStallAdc);
        addressToTypeMap.put(ADDRESS_ANGLE_SENSOR_STALL_ADC, 1); // Int16
        addressToEditTextMap.put(ADDRESS_ANGLE_SENSOR_STALL_SECONDS, binding.valueAngleSensorStallSeconds);
        addressToTypeMap.put(ADDRESS_ANGLE_SENSOR_STALL_SECONDS, 1); // Int16
        addressToEditTextMap.put(ADDRESS_VALVE_OPENING_CONTROL_ERROR, binding.valueValveOpeningControlError);
        addressToTypeMap.put(ADDRESS_VALVE_OPENING_CONTROL_ERROR, 0); // Float
        addressToEditTextMap.put(ADDRESS_ANGLE_SENSOR_SAMPLING_PERIOD, binding.valueAngleSensorSamplingPeriod);
        addressToTypeMap.put(ADDRESS_ANGLE_SENSOR_SAMPLING_PERIOD, 1); // Int16
        addressToEditTextMap.put(ADDRESS_MOTOR_STALL_CURRENT, binding.valueMotorStallCurrent);
        addressToTypeMap.put(ADDRESS_MOTOR_STALL_CURRENT, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP1_ZERO_ORIGINAL_RESISTANCE, binding.valueTemp1ZeroOriginalResistance);
        addressToTypeMap.put(ADDRESS_TEMP1_ZERO_ORIGINAL_RESISTANCE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP1_FULL_ORIGINAL_RESISTANCE, binding.valueTemp1FullOriginalResistance);
        addressToTypeMap.put(ADDRESS_TEMP1_FULL_ORIGINAL_RESISTANCE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP1_ZERO_RESISTANCE, binding.valueTemp1ZeroResistance);
        addressToTypeMap.put(ADDRESS_TEMP1_ZERO_RESISTANCE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP1_FULL_RESISTANCE, binding.valueTemp1FullResistance);
        addressToTypeMap.put(ADDRESS_TEMP1_FULL_RESISTANCE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP2_ZERO_ORIGINAL_RESISTANCE, binding.valueTemp2ZeroOriginalResistance);
        addressToTypeMap.put(ADDRESS_TEMP2_ZERO_ORIGINAL_RESISTANCE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP2_FULL_ORIGINAL_RESISTANCE, binding.valueTemp2FullOriginalResistance);
        addressToTypeMap.put(ADDRESS_TEMP2_FULL_ORIGINAL_RESISTANCE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP2_ZERO_RESISTANCE, binding.valueTemp2ZeroResistance);
        addressToTypeMap.put(ADDRESS_TEMP2_ZERO_RESISTANCE, 1); // Int16
        addressToEditTextMap.put(ADDRESS_TEMP2_FULL_RESISTANCE, binding.valueTemp2FullResistance);
        addressToTypeMap.put(ADDRESS_TEMP2_FULL_RESISTANCE, 1); // Int16
    }

    /**
     * 设置所有写入按钮的点击事件
     */
    private void setupWriteButtons() {
        // 用户设定区域 - Float类型
        binding.writePressure1ZeroCurrentButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE1_ZERO_CURRENT, binding.valuePressure1ZeroCurrent.getText().toString(), "压力传感器1_零点电流"));
        binding.writePressure1FullCurrentButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE1_FULL_CURRENT, binding.valuePressure1FullCurrent.getText().toString(), "压力传感器1_满度电流"));
        binding.writePressure1ZeroPressureButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE1_ZERO_PRESSURE, binding.valuePressure1ZeroPressure.getText().toString(), "压力传感器1_零点压力"));
        binding.writePressure1FullPressureButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE1_FULL_PRESSURE, binding.valuePressure1FullPressure.getText().toString(), "压力传感器1_满度压力"));
        binding.writePressure2ZeroCurrentButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE2_ZERO_CURRENT, binding.valuePressure2ZeroCurrent.getText().toString(), "压力传感器2_零点电流"));
        binding.writePressure2FullCurrentButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE2_FULL_CURRENT, binding.valuePressure2FullCurrent.getText().toString(), "压力传感器2_满度电流"));
        binding.writePressure2ZeroPressureButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE2_ZERO_PRESSURE, binding.valuePressure2ZeroPressure.getText().toString(), "压力传感器2_零点压力"));
        binding.writePressure2FullPressureButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE2_FULL_PRESSURE, binding.valuePressure2FullPressure.getText().toString(), "压力传感器2_满度压力"));
        binding.writeTemp1CoeffAButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP1_COEFF_A, binding.valueTemp1CoeffA.getText().toString(), "温度传感器1_系数A"));
        binding.writeTemp1CoeffBButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP1_COEFF_B, binding.valueTemp1CoeffB.getText().toString(), "温度传感器1_系数B"));
        binding.writeTemp1CoeffCButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP1_COEFF_C, binding.valueTemp1CoeffC.getText().toString(), "温度传感器1_系数C"));
        binding.writeTemp1ZeroDriftButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP1_ZERO_DRIFT, binding.valueTemp1ZeroDrift.getText().toString(), "温度传感器1_温度零漂"));
        binding.writeTemp2CoeffAButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP2_COEFF_A, binding.valueTemp2CoeffA.getText().toString(), "温度传感器2_系数A"));
        binding.writeTemp2CoeffBButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP2_COEFF_B, binding.valueTemp2CoeffB.getText().toString(), "温度传感器2_系数B"));
        binding.writeTemp2CoeffCButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP2_COEFF_C, binding.valueTemp2CoeffC.getText().toString(), "温度传感器2_系数C"));
        binding.writeTemp2ZeroDriftButton.setOnClickListener(v -> writeFloatValue(ADDRESS_TEMP2_ZERO_DRIFT, binding.valueTemp2ZeroDrift.getText().toString(), "温度传感器2_温度零漂"));
        binding.writeAutoControlPButton.setOnClickListener(v -> writeFloatValue(ADDRESS_AUTO_CONTROL_P, binding.valueAutoControlP.getText().toString(), "自动控温-P系数"));
        binding.writeAutoControlIButton.setOnClickListener(v -> writeFloatValue(ADDRESS_AUTO_CONTROL_I, binding.valueAutoControlI.getText().toString(), "自动控温-I系数"));
        binding.writeAutoControlDButton.setOnClickListener(v -> writeFloatValue(ADDRESS_AUTO_CONTROL_D, binding.valueAutoControlD.getText().toString(), "自动控温-D系数"));
        binding.writeAutoControlPeriodButton.setOnClickListener(v -> writeInt16Value(ADDRESS_AUTO_CONTROL_PERIOD, binding.valueAutoControlPeriod.getText().toString(), "自动控制周期"));

        // 出厂设定区域
        binding.writePressure1ZeroVoltageButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE1_ZERO_VOLTAGE, binding.valuePressure1ZeroVoltage.getText().toString(), "压力传感器1_零点电压"));
        binding.writePressure1FullVoltageButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE1_FULL_VOLTAGE, binding.valuePressure1FullVoltage.getText().toString(), "压力传感器1_满度电压"));
        binding.writePressure2ZeroVoltageButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE2_ZERO_VOLTAGE, binding.valuePressure2ZeroVoltage.getText().toString(), "压力传感器2_零点电压"));
        binding.writePressure2FullVoltageButton.setOnClickListener(v -> writeFloatValue(ADDRESS_PRESSURE2_FULL_VOLTAGE, binding.valuePressure2FullVoltage.getText().toString(), "压力传感器2_满度电压"));
        binding.writeDacZeroButton.setOnClickListener(v -> writeInt16Value(ADDRESS_DAC_ZERO, binding.valueDacZero.getText().toString(), "DAC输出零点"));
        binding.writeDacFullButton.setOnClickListener(v -> writeInt16Value(ADDRESS_DAC_FULL, binding.valueDacFull.getText().toString(), "DAC输出满度"));
        binding.writeMultiTurnAngleZeroButton.setOnClickListener(v -> writeFloatValue(ADDRESS_MULTI_TURN_ANGLE_ZERO, binding.valueMultiTurnAngleZero.getText().toString(), "多圈角度传感器_零点角度"));
        binding.writeOpeningAngleZeroButton.setOnClickListener(v -> writeFloatValue(ADDRESS_OPENING_ANGLE_ZERO, binding.valueOpeningAngleZero.getText().toString(), "开度传感器_零点角度"));
        binding.writeOpeningAngleFullButton.setOnClickListener(v -> writeFloatValue(ADDRESS_OPENING_ANGLE_FULL, binding.valueOpeningAngleFull.getText().toString(), "开度传感器_满度角度"));
        binding.writeOpeningZeroButton.setOnClickListener(v -> writeFloatValue(ADDRESS_OPENING_ZERO, binding.valueOpeningZero.getText().toString(), "开度传感器_零点开度"));
        binding.writeOpeningFullButton.setOnClickListener(v -> writeFloatValue(ADDRESS_OPENING_FULL, binding.valueOpeningFull.getText().toString(), "开度传感器_满度开度"));
        binding.writeMaxRotationTurnsButton.setOnClickListener(v -> writeInt16Value(ADDRESS_MAX_ROTATION_TURNS, binding.valueMaxRotationTurns.getText().toString(), "最大转动圈数"));
        binding.writeSensorValidityConfigButton.setOnClickListener(v -> writeStringValue(ADDRESS_SENSOR_VALIDITY_CONFIG, binding.valueSensorValidityConfig.getText().toString(), "传感器有效性配置"));
        binding.writeTempSensorTypeButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP_SENSOR_TYPE, binding.valueTempSensorType.getText().toString(), "温度传感器类型"));
        binding.writeEquiSerialNumberButton.setOnClickListener(v -> writeUint32Value(ADDRESS_EQUI_SERIAL_NUMBER, binding.valueEquiSerialNumber.getText().toString(), "equi序列号"));
        binding.writeAngleSensorStallAdcButton.setOnClickListener(v -> writeInt16Value(ADDRESS_ANGLE_SENSOR_STALL_ADC, binding.valueAngleSensorStallAdc.getText().toString(), "角度传感器堵转(ADC)"));
        binding.writeAngleSensorStallSecondsButton.setOnClickListener(v -> writeInt16Value(ADDRESS_ANGLE_SENSOR_STALL_SECONDS, binding.valueAngleSensorStallSeconds.getText().toString(), "角度传感器堵转(秒)"));
        binding.writeValveOpeningControlErrorButton.setOnClickListener(v -> writeFloatValue(ADDRESS_VALVE_OPENING_CONTROL_ERROR, binding.valueValveOpeningControlError.getText().toString(), "阀开度控制误差"));
        binding.writeAngleSensorSamplingPeriodButton.setOnClickListener(v -> writeInt16Value(ADDRESS_ANGLE_SENSOR_SAMPLING_PERIOD, binding.valueAngleSensorSamplingPeriod.getText().toString(), "角度传感器采样周期"));
        binding.writeMotorStallCurrentButton.setOnClickListener(v -> writeInt16Value(ADDRESS_MOTOR_STALL_CURRENT, binding.valueMotorStallCurrent.getText().toString(), "电机堵转电流"));
        binding.writeTemp1ZeroOriginalResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP1_ZERO_ORIGINAL_RESISTANCE, binding.valueTemp1ZeroOriginalResistance.getText().toString(), "温度传感器1_零点原始电阻"));
        binding.writeTemp1FullOriginalResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP1_FULL_ORIGINAL_RESISTANCE, binding.valueTemp1FullOriginalResistance.getText().toString(), "温度传感器1_满度原始电阻"));
        binding.writeTemp1ZeroResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP1_ZERO_RESISTANCE, binding.valueTemp1ZeroResistance.getText().toString(), "温度传感器1_零点电阻"));
        binding.writeTemp1FullResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP1_FULL_RESISTANCE, binding.valueTemp1FullResistance.getText().toString(), "温度传感器1_满度电阻"));
        binding.writeTemp2ZeroOriginalResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP2_ZERO_ORIGINAL_RESISTANCE, binding.valueTemp2ZeroOriginalResistance.getText().toString(), "温度传感器2_零点原始电阻"));
        binding.writeTemp2FullOriginalResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP2_FULL_ORIGINAL_RESISTANCE, binding.valueTemp2FullOriginalResistance.getText().toString(), "温度传感器2_满度原始电阻"));
        binding.writeTemp2ZeroResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP2_ZERO_RESISTANCE, binding.valueTemp2ZeroResistance.getText().toString(), "温度传感器2_零点电阻"));
        binding.writeTemp2FullResistanceButton.setOnClickListener(v -> writeInt16Value(ADDRESS_TEMP2_FULL_RESISTANCE, binding.valueTemp2FullResistance.getText().toString(), "温度传感器2_满度电阻"));
    }

    /**
     * 读取所有值 - 一次性读取所有寄存器，然后从返回值中提取需要的值
     */
    private void readAllValues() {
        Toast.makeText(getActivity(), "开始读取所有值...", Toast.LENGTH_SHORT).show();
        
        try {
            isBatchReading = true;
            // 一次性读取从起始地址开始的所有寄存器
            byte[] bytes = ModbusRTUHelper.readHoldingRegisters(1, BATCH_READ_START_ADDRESS, BATCH_READ_REGISTER_COUNT);
            System.out.println("发送批量读取所有寄存器:>>>" + BleController.getInstance().bytesToHexString(bytes));

            BleController.getInstance().writeBuffer(bytes, new OnWriteCallback() {
                @Override
                public void onSuccess() {
                    // 读取请求发送成功，等待响应
                }

                @Override
                public void onFailed(int state) {
                    Toast.makeText(getActivity(), "批量读取失败！", Toast.LENGTH_SHORT).show();
                    isBatchReading = false;
                }
            });
        } catch (ModbusError e) {
            Toast.makeText(getActivity(), "批量读取异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            isBatchReading = false;
        }
    }

    /**
     * 从批量读取的响应中提取指定地址的值
     * @param dataBytes 数据部分（不包含设备地址、功能码、字节数、CRC）
     * @param address 要提取的地址
     * @return 提取的值（根据类型返回Float、Int16或Uint32）
     */
    private Object extractValueFromBatchData(byte[] dataBytes, int address) {
        // 计算地址在批量数据中的偏移量（相对于起始地址）
        int offset = address - BATCH_READ_START_ADDRESS;
        
        // 检查偏移量是否有效
        if (offset < 0 || offset >= BATCH_READ_REGISTER_COUNT) {
            return null;
        }
        
        // 获取数据类型
        Integer type = addressToTypeMap.get(address);
        if (type == null) {
            return null;
        }
        
        // 根据数据类型提取值
        if (type == 0) { // Float - 需要2个寄存器（4个字节）
            if (offset + 1 >= BATCH_READ_REGISTER_COUNT) {
                return null;
            }
            int byteOffset = offset * 2; // 每个寄存器2个字节
            if (byteOffset + 3 >= dataBytes.length) {
                return null;
            }
            byte[] floatBytes = Arrays.copyOfRange(dataBytes, byteOffset, byteOffset + 4);
            return ByteUtil.bytesToFloat(floatBytes);
        } else if (type == 1 || type == 3) { // Int16 或 String(按Int16处理) - 需要1个寄存器（2个字节）
            int byteOffset = offset * 2;
            if (byteOffset + 1 >= dataBytes.length) {
                return null;
            }
            return ByteUtil.bytesToInt16(dataBytes[byteOffset], dataBytes[byteOffset + 1]);
        } else if (type == 2) { // Uint32 - 需要2个寄存器（4个字节）
            if (offset + 1 >= BATCH_READ_REGISTER_COUNT) {
                return null;
            }
            int byteOffset = offset * 2;
            if (byteOffset + 3 >= dataBytes.length) {
                return null;
            }
            return ByteUtil.bytesToUint32(dataBytes[byteOffset], dataBytes[byteOffset + 1], 
                                         dataBytes[byteOffset + 2], dataBytes[byteOffset + 3]);
        }
        
        return null;
    }

    /**
     * 写入Float类型的值
     */
    private void writeFloatValue(int address, String valueStr, String name) {
        if (valueStr == null || valueStr.trim().isEmpty()) {
            Toast.makeText(getActivity(), "请输入" + name + "的值", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!ToolsUtil.isFloatType(valueStr)) {
            Toast.makeText(getActivity(), name + "的值格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            float value = Float.parseFloat(valueStr);
            byte[] floatBytes = ByteUtil.floatToBytes(value);
            
            // 将float的4个字节转换为2个16位寄存器
            int[] writeInt16 = new int[REGISTER_COUNT_FLOAT];
            writeInt16[0] = ByteUtil.bytesToUint16(floatBytes[0], floatBytes[1]);
            writeInt16[1] = ByteUtil.bytesToUint16(floatBytes[2], floatBytes[3]);

            byte[] bytes = ModbusRTUHelper.writeHoldingRegisters(1, address, REGISTER_COUNT_FLOAT, writeInt16);
            System.out.println("发送写入" + name + ":>>>" + BleController.getInstance().bytesToHexString(bytes));

            BleController.getInstance().writeBuffer(bytes, new OnWriteCallback() {
                @Override
                public void onSuccess() {
                    Toast.makeText(getActivity(), name + "写入成功！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailed(int state) {
                    Toast.makeText(getActivity(), name + "写入失败！", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (ModbusError e) {
            Toast.makeText(getActivity(), name + "写入异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        } catch (NumberFormatException e) {
            Toast.makeText(getActivity(), name + "的值格式不正确", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 写入Int16类型的值
     */
    private void writeInt16Value(int address, String valueStr, String name) {
        if (valueStr == null || valueStr.trim().isEmpty()) {
            Toast.makeText(getActivity(), "请输入" + name + "的值", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            int value = Integer.parseInt(valueStr);
            if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
                Toast.makeText(getActivity(), name + "的值超出范围", Toast.LENGTH_SHORT).show();
                return;
            }

            byte[] bytes = ModbusRTUHelper.writeSingleRegister(1, address, value);
            System.out.println("发送写入" + name + ":>>>" + BleController.getInstance().bytesToHexString(bytes));

            BleController.getInstance().writeBuffer(bytes, new OnWriteCallback() {
                @Override
                public void onSuccess() {
                    Toast.makeText(getActivity(), name + "写入成功！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailed(int state) {
                    Toast.makeText(getActivity(), name + "写入失败！", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (ModbusError e) {
            Toast.makeText(getActivity(), name + "写入异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        } catch (NumberFormatException e) {
            Toast.makeText(getActivity(), name + "的值格式不正确", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 写入Uint32类型的值
     */
    private void writeUint32Value(int address, String valueStr, String name) {
        if (valueStr == null || valueStr.trim().isEmpty()) {
            Toast.makeText(getActivity(), "请输入" + name + "的值", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            long value = Long.parseLong(valueStr);
            if (value < 0 || value > 0xFFFFFFFFL) {
                Toast.makeText(getActivity(), name + "的值超出范围", Toast.LENGTH_SHORT).show();
                return;
            }

            // 将Uint32转换为2个16位寄存器
            int[] writeInt16 = new int[REGISTER_COUNT_UINT32];
            writeInt16[0] = (int)((value >> 16) & 0xFFFF);
            writeInt16[1] = (int)(value & 0xFFFF);

            byte[] bytes = ModbusRTUHelper.writeHoldingRegisters(1, address, REGISTER_COUNT_UINT32, writeInt16);
            System.out.println("发送写入" + name + ":>>>" + BleController.getInstance().bytesToHexString(bytes));

            BleController.getInstance().writeBuffer(bytes, new OnWriteCallback() {
                @Override
                public void onSuccess() {
                    Toast.makeText(getActivity(), name + "写入成功！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailed(int state) {
                    Toast.makeText(getActivity(), name + "写入失败！", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (ModbusError e) {
            Toast.makeText(getActivity(), name + "写入异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        } catch (NumberFormatException e) {
            Toast.makeText(getActivity(), name + "的值格式不正确", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 写入String类型的值（传感器有效性配置等）
     */
    private void writeStringValue(int address, String valueStr, String name) {
        // 字符串类型可能需要特殊处理，这里先按Int16写入
        // 如果字符串是十六进制格式，需要转换
        if (valueStr == null || valueStr.trim().isEmpty()) {
            Toast.makeText(getActivity(), "请输入" + name + "的值", Toast.LENGTH_SHORT).show();
            return;
        }

        // 尝试解析为整数（可能是十六进制字符串）
        try {
            int value;
            if (valueStr.startsWith("0x") || valueStr.startsWith("0X")) {
                value = Integer.parseInt(valueStr.substring(2), 16);
            } else {
                value = Integer.parseInt(valueStr);
            }
            writeInt16Value(address, String.valueOf(value), name);
        } catch (NumberFormatException e) {
            Toast.makeText(getActivity(), name + "的值格式不正确", Toast.LENGTH_SHORT).show();
        }
    }

    public void exitFragment() {
        BleController.getInstance().unregistReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY);
    }

    public void enterFragment() {
        BleController.getInstance().unregistReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY);
        
        // 接收数据的监听
        BleController.getInstance().registReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY, new OnReceiverCallback() {
            @Override
            public void onRecive(byte[] value) {
                if (binding == null) {
                    return;
                }

                System.out.println("接收：>>" + BleController.getInstance().bytesToHexString(value));
                
                // 检查响应长度
                if (value.length < 5) {
                    return;
                }

                // 检查是否是读取保持寄存器的响应 (功能码0x03)
                if (value[1] != 0x03) {
                    return;
                }

                // 获取数据长度
                int dataLength = value[2] & 0xFF;
                
                // 如果是批量读取响应
                if (isBatchReading) {
                    // 检查数据长度是否匹配：应该返回 BATCH_READ_REGISTER_COUNT * 2 个字节
                    int expectedDataLength = BATCH_READ_REGISTER_COUNT * 2;
                    if (dataLength != expectedDataLength) {
                        System.out.println("批量读取数据长度不匹配，期望：" + expectedDataLength + "，实际：" + dataLength);
                        isBatchReading = false;
                        return;
                    }
                    
                    // 提取数据部分（跳过设备地址、功能码、字节数，最后2个字节是CRC）
                    byte[] dataBytes = Arrays.copyOfRange(value, 3, 3 + dataLength);
                    
                    // 遍历所有地址，从批量数据中提取对应的值
                    for (Map.Entry<Integer, EditText> entry : addressToEditTextMap.entrySet()) {
                        int address = entry.getKey();
                        EditText editText = entry.getValue();
                        
                        Object extractedValue = extractValueFromBatchData(dataBytes, address);
                        if (extractedValue != null) {
                            editText.setText(String.valueOf(extractedValue));
                        }
                    }
                    
                    isBatchReading = false;
                    Toast.makeText(getActivity(), "所有值读取完成！", Toast.LENGTH_SHORT).show();
                } else {
                    // 单个读取响应（保留原有逻辑，用于单个写入后的读取确认等）
                    // 这里可以保留原有的单个读取逻辑，但当前主要使用批量读取
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        enterFragment();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        exitFragment();
        binding = null;
    }
}

